import { PureComponent } from 'react';
import { ErrorLike } from './ErrorFallback';

// eslint-disable-next-line @typescript-eslint/ban-types
type AnyObject = {};

export type ErrorBoundaryState<S> = {
  error?: ErrorLike | null,
} & S

export type ErrorBoundaryProps<P> = {
  onError?: (error: ErrorLike) => void;
} & P

export class ErrorBoundary<P = AnyObject, S = AnyObject> extends PureComponent<ErrorBoundaryProps<P>, ErrorBoundaryState<S>> {

  static getDerivedStateFromError(error: Error) {
    return { error };
  }

  componentDidCatch(error: Error): void {
    this.onError(error);
  }

  onError(error: Error): void {
    if (typeof this.props.onError === 'function') {
      this.props.onError(error);
    }
  }
}
